﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;

namespace Eneta.Portal.Forum.Common.Controls
{
    public class OWSChoiceField : OWSBase
    {
        // Fields
        private ListItemCollection _items = new ListItemCollection();

        // Methods
        private string GetChoicesJScript()
        {
            string str = "";
            foreach (ListItem item in this._items)
            {
                str = str + string.Format("fld.AddChoice(\"{0}\",\"{1}\");", item.Text.Replace(@"\", @"\\").Replace("\"", "\\\""), item.Value.Replace(@"\", @"\\").Replace("\"", "\\\""));
            }
            return str;
        }

        protected override void Render(HtmlTextWriter wtr)
        {
            wtr.Write("<SCRIPT>fld = new ChoiceField(frm, \"{0}\", \"{1}\", \"{2}\");fld.format = \"{3}\";{4};fld.fRequired = {5};fld.IMEMode=\"\";fld.BuildUI();</SCRIPT>", new object[] { this.UniqueID, base.Display, base.JavaScriptValue, this.ChoiceFormat.ToString(), this.GetChoicesJScript(), base.Required.ToString().ToLower() });
            wtr.Write("&nbsp;<br><SPAN class=ms-formdescription ID={0}>{1}</SPAN>", this.UniqueID, this.Description);
        }

        // Properties
        public SPChoiceFormatType ChoiceFormat
        {
            get
            {
                if (this.ViewState["ChoiceFormat"] == null)
                {
                    this.ChoiceFormat = 0;
                }
                return (SPChoiceFormatType)this.ViewState["ChoiceFormat"];
            }
            set
            {
                this.ViewState["ChoiceFormat"] = value;
            }
        }

        public ListItemCollection Items
        {
            get
            {
                return this._items;
            }
        }

        public override string Text
        {
            get
            {
                ListItem item = null;
                for (int i = 0; (i < this.Items.Count) && (item == null); i++)
                {
                    if (this.Items[i].Value == this.Value)
                    {
                        item = this.Items[i];
                    }
                }
                if (item == null)
                {
                    return "";
                }
                return item.Text;
            }
        }
    }

 

}
